<template>
  <div class="user-edit-container">
    <!-- 返回按钮 -->
    <button class="back-btn" @click="handleBack">
      <svg viewBox="0 0 24 24" width="24" height="24">
        <path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/>
      </svg>
    </button>
    
    <div class="avatar-wrap">
      <img :src="form.avatar || defaultAvatar" alt="用户头像" class="avatar" />
    </div>
    <form class="edit-form"  @submit.prevent="handleSubmit">
      <div class="form-item">
        <label class="form-label">用户名</label>
        <input type="text" class="form-input" v-model="form.userId" disabled />
      </div>
      <div class="form-item">
        <label class="form-label">昵称</label>
        <input type="text" class="form-input" v-model="form.name" />
      </div>
      <div class="form-item">
        <label class="form-label">邮箱</label>
        <input type="email" class="form-input" v-model="form.email" />
      </div>
      <div class="form-item">
        <label class="form-label">电话</label>
        <input type="tel" class="form-input" v-model="form.phone" />
      </div>
      <div class="form-item">
        <label class="form-label">地址</label>
        <textarea class="form-textarea" v-model="form.address" @keydown.enter.prevent="handleSubmit"></textarea>
      </div>
      <div class="form-item">
        <label class="form-label">自我介绍</label>
        <textarea class="form-textarea" v-model="form.description" @keydown.enter.prevent="handleSubmit"></textarea>
      </div>
      <div class="form-item btn-group">
        <button 
          type="submit" 
          class="submit-btn" 
          :disabled="isFormUnchanged"
        >
          确定
        </button>
        <button 
          type="button" 
          class="cancel-btn" 
          @click="handleCancel"
          :disabled="isFormUnchanged"
        >
          取消
        </button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, watch, toRaw } from 'vue'
import router from '@/router';
import {findUserInfoByUserId,updateByUserId} from "@/api/life";
import { ElMessage } from "element-plus";
const form = reactive({
  avatar:'',
  userId: '',
  name: '',
  email: '',
  phone: '',
  address: '',
  description: ''
})

// 默认头像
const defaultAvatar = "https://picsum.photos/200/200";
// 存储原始数据用于对比和恢复
const originalForm = ref({})
// 表单是否未修改（控制按钮禁用状态）
const isFormUnchanged = ref(true)

//获取用户的userId（从localStorage读取实际登录用户ID）
const getUserId = () => {
  const userStr = localStorage.getItem("user");
  const user = userStr ? JSON.parse(userStr) : null;
  if (user && user.userId) {
    form.userId = user.userId;
    console.log("userId更新为:", form.userId);
    getUserNameAndAvatar(form.userId);
  } else {
    console.log("localStorage 中未找到有效的 user 数据,使用默认userId=3");
  }
};

//获取用户头像,姓名,用户描述,地址
const getUserNameAndAvatar= async(userId) =>{
  try {
    const res =  await findUserInfoByUserId(userId)
    console.log("接收到的NameAndAvatar数据", res.data);
    // 赋值表单数据
    form.avatar = res.data.avatar
    form.name = res.data.name
    form.address = res.data.address
    form.description = res.data.description
    form.email = res.data.email
    form.phone = res.data.phone
    // 保存原始数据（深拷贝）
    originalForm.value = JSON.parse(JSON.stringify(toRaw(form)))
    // 初始化监听
    initFormWatcher()
  } catch (error) {
    console.error("NameAndAvatar数据请求失败,请重试");
  }
}

// 初始化表单监听
const initFormWatcher = () => {
  watch(
    form,
    () => {
      // 对比当前数据与原始数据
      isFormUnchanged.value = JSON.stringify(toRaw(form)) === JSON.stringify(originalForm.value)
    },
    { deep: true }
  )
}

// 提交表单  修改用户信息
const handleSubmit = async () => {
  console.log('提交的表单数据：', form);
  try {
    const res = await updateByUserId(form);
    if (res.code === 200) {
      ElMessage.success('修改成功');
      // 延迟 300ms 跳转（等待消息提示显示）
      await new Promise(resolve => setTimeout(resolve, 300));
      await handleBack(); // 等待路由跳转完成
    } else {
      ElMessage.error(res.msg || '修改失败，请重试');
      await handleCancel();
    }
  } catch (error) {
    ElMessage.error('请求出错，请稍后再试');
    console.error('提交失败', error);
    await handleCancel();
  }
};

// 取消编辑
const handleCancel = async() => {
  // 恢复原始数据
  Object.assign(form, originalForm.value)
}


// 修改返回方法，明确返回路由跳转的 Promise
const handleBack = async () => {
  // 明确返回路由跳转的 Promise
  try {
    await router.push('/LifePerson');
    console.log('路由跳转成功');
  } catch (err) {
    console.error('路由跳转失败:', err);
  }
};
// 初始化
onMounted(() => {
  getUserId();
});
</script>

<style scoped>
.user-edit-container {
  position: relative;
  width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 返回按钮样式 */
.back-btn {
  position: absolute;
  top: 15px;
  left: 15px;
  width: 30px;
  height: 30px;
  background: #f5f5f5;
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #e5e5e5;
  color: #333;
}

.avatar-wrap {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.edit-form {
  margin-top: 20px;
}

.form-item {
  margin-bottom: 16px;
}

.form-label {
  display: inline-block;
  width: 80px;
  text-align: right;
  margin-right: 10px;
}

.form-input,
.form-textarea {
  width: 240px;
  padding: 6px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
}

.form-textarea {
  height: 80px;
  resize: none;
}

/* 按钮组样式 */
.btn-group {
  margin-left: 90px;
  display: flex;
  gap: 10px;
}

.submit-btn {
  padding: 6px 20px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #66b1ff;
}

.submit-btn:disabled,
.cancel-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cancel-btn {
  padding: 6px 20px;
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e5e5e5;
}
</style>